import { View, Text, Image, Textarea } from "@tarojs/components";
import Taro, { useLoad, useUnload } from "@tarojs/taro";
import { Button, Cell, CellGroup, Dialog, Empty, NavBar, Picker } from "@nutui/nutui-react-taro";
import { Share, More, Cart, ArrowLeft, Close } from '@nutui/icons-react-taro'
import { c } from "../../common";
import { useEffect, useState } from "react";
import { getParams, navigateTo } from "../../common/_";

import { selectEnts, selectExamDetail, startExam } from "../../api/ceshi";
import SelectItem from "../../components/selectItem";
import InputItem from "../../components/inputItem";
import dayjs from "dayjs";
import { getStore } from "../../utils/localStore";
import { addApply } from "../../api/apply";
import { selectDict, selectDictById, selectDictByParentId, selectDicts } from "../../api/system";
import { getGlobalData, getSystemEnumValue, initGlobalData } from "../../utils/globalData.js";
import useNavInfo from "../../hooks/useNavInfo.js";
import NavTab from "../../components/navTab/index.jsx";
import "./index.scss";

export default function Apply(props) {

  const [isVisible1, setIsVisible1] = useState(false)
  const [areaList, setAreaList] = useState([])
  const [isVisible2, setIsVisible2] = useState(false)
  const [timeList, setTimeList] = useState([])

  const [isVisible3, setIsVisible3] = useState(false)
  const [isVisible4, setIsVisible4] = useState(false)

  const [companyList, setCompanyList] = useState([])
  const [companyListSelect, setCompanyListSelect] = useState([])

  useEffect(() => {
    getGennerDate()
    selectDicts()
  }, [])

  useEffect(() => {
    // console.log(getParams());
    if (getParams()) {
      initData(getParams())
    }
    // initData(props.item)
  }, [areaList, companyList])

  const initData = (data) => {
    setId(data.id)
    setJurisdiction(matchDict(areaList, data.jurisdiction))
    setJurisdictionCode(data.jurisdiction)
    setCategory(matchDict(companyList, data.category))
    setCategoryCode(data.category)
    setEnterpriseName(data.enterpriseName)
    // setTrainingTime(data.trainingTime.substr(0, 16))
    setNumber(data.number)
    setRemark(data.remark)
    setContactName(data.contactName)
  }

  const matchDict = (list, id) => {
    console.log("companyList", list);
    for (let index = 0; index < list.length; index++) {
      const element = list[index];
      if (element.value == id) {
        // console.log('value',element.text);
        return element.text
      }
    }
  }

  async function selectCompany(val) {
    const { data } = await selectEnts({ entName: val })
    setCompanyListSelect(data)
  }

  function getEnterVal(item) {
    setEnterpriseName(item.enterpriseName)
    setCompanyListSelect([])
  }

  const selectDicts = async () => {
    initGlobalData().then(res => {

      const data1 = getGlobalData(13)
      const data2 = getGlobalData(77)

      let arr = []
      data1?.forEach(v => {
        arr.push({ text: v.name, value: v.code })
      })
      setAreaList(arr)
      let arr1 = []
      data2?.forEach(v => {
        arr1.push({ text: v.name, value: v.code })
      })
      setCompanyList(arr1)


    })


  }


  const getGennerDate = () => {
    const today = dayjs();
    let dates = [];
    for (let i = 1; i <= 30; i++) {
      const date = today.add(i + 1, 'day').format('MM-DD'); // i + 1 因为起始点是后两天
      dates.push({ text: date, value: date });
    }
    setTimeList([dates, [
      { text: "09:00", value: "09:00" },
      { text: "10:00", value: "10:00" },
      { text: "11:00", value: "11:00" },
      { text: "15:00", value: "15:00" },
      { text: "16:00", value: "16:00" },
      { text: "17:00", value: "17:00" }
    ]])
  }
  jurisdiction
  const confirmPicker = (
    options,
    values
  ) => {
    let description = ''
    options.forEach((option) => {
      description += ` ${option.text}`
    })
    console.log(description);
    setCategory(description)
    // setMutilDesc(description)
  }
  const changePicker = (options, values, columnIndex) => {
    console.log('picker onChange', columnIndex, values, options)
  }

  const [jurisdiction, setJurisdiction] = useState('')
  const [jurisdictionCode, setJurisdictionCode] = useState('')

  const [id, setId] = useState("")
  const [auditState, setAuditState] = useState(0)
  const [category, setCategory] = useState('')
  const [categoryCode, setCategoryCode] = useState('')
  const [enterpriseName, setEnterpriseName] = useState('')
  const [number, setNumber] = useState('')
  const [contactName, setContactName] = useState('')
  const [trainingTime, setTrainingTime] = useState('')
  const [phone, setPhone] = useState(getStore("userInfo").loginCode)
  const [remark, setRemark] = useState("")

  const { statusBarHeight, screenWidth } = useNavInfo();

  const submit = async () => {

    console.log(dayjs().format('YYYY-'));

    const params = {
      jurisdiction: jurisdictionCode,
      category: categoryCode,
      enterpriseName,
      number,
      contactName,
      contactName,
      trainingTime: dayjs().format('YYYY-') + trainingTime + ':00',
      phone,
      remark,
    }

    const { success, msg } = await addApply(params)
    if (success) {
      Taro.showToast({
        title: "新增成功",
        icon: 'none'
      })
      setIsVisible4(false)
      // const {changeCur} = props
      // changeCur(2)
      // Taro.navigateBack()
      // Taro.eventCenter.trigger('reList', {});
      _handleback()
    } else {
      setIsVisible4(false)
      Taro.showModal({
        content: msg
      })
    }
  }

  function verify() {
    if (!jurisdiction) return "请选择所在管辖区";
    if (!category) return "请选择单位类别";
    if (!enterpriseName) return "请输入申请单位名称";
    if (!number) return "请输入培训人数";
    if (!contactName) return "请输入联系人姓名";
    if (!phone) return "请输入联系电话";
    if (!trainingTime) return "请选择培训时间";
  }

  function _handleback() {
    Taro.navigateBack({
      delta: 1
    })
  }

  const [tabCur, setTabCur] = useState(1)

  const tabChange = (cur) => {
    setTabCur(cur)
  }

  const [cur, setCur] = useState(1)

  const pageClick = () => {
    if (companyListSelect.length > 0) {
      setCompanyListSelect([])
    }
  }

  useUnload(() => {
    _handleback()
  })

  function _handleback() {
    Taro.switchTab({
      url: '/pages/home/index'
    })
  }

  return (
    <View className="wrap" onclick={() => pageClick()}>
      <NavTab
        tabCur={cur}
        tabList={[{ name: '培训申请', id: 1 }, { name: '培训记录', id: 2 }]}
        onChangeCallback={(cur) => {
          console.log(cur);
          if (cur === 2) {
            navigateTo("/pages/training-list/index")
          }
          // setCur(cur)
        }}
        customBack={() => {
          _handleback()
        }}
      />
      {/* <NavBar
        fixed
        style={{ backgroundColor: "#fff", height: statusBarHeight + 50, paddingTop: 24 }}
        back={
          <>
            <ArrowLeft style={{ marginTop: 24 }} />
          </>
        }
        onBackClick={(e) => _handleback()}
      >
        <View className="customTabWrap">

          <View style={{backgroundColor: tabCur === 1 ? '#4F84F6':'#fff'}} onclick={()=>tabChange(1)} className="tabLeft">
            <Text style={{color: tabCur === 1 ? '#fff':'#111111'}}>学习统计</Text>
          </View>
          <View style={{backgroundColor: tabCur === 2 ? '#4F84F6':'#fff'}} onclick={()=>tabChange(2)} className="tabRight">
            <Text style={{color: tabCur === 2 ? '#fff':'#111111'}}>学习统计</Text>
          </View>
        </View>
      </NavBar> */}

      <View className="pxTip" style={{ marginTop: statusBarHeight + 24 }}>
        <Text>消防部门培训不收费</Text>
      </View>

      <View className="formWrap" >
        <SelectItem
          label={"所在辖区"}
          value={jurisdiction}
          placeholder="请选择所在管辖区"
          required
          style={{ borderTopLeftRadius: 16, borderTopRightRadius: 16, }}
          onclick={() => {
            setIsVisible1(true)
          }}
        />
        <SelectItem
          label={"单位类别"}
          value={category}
          placeholder={"请选择单位类别"}
          required
          onclick={() => {
            setIsVisible3(true)
          }}
        />
        <View className="companyWrap">
          <InputItem
            label={"申请单位名称"}
            value={enterpriseName}
            required
            placeholder={"请输入单位名称"}
            onChange={(val) => {
              setEnterpriseName(val)
              selectCompany(val)
            }}
          />
          {

            enterpriseName && companyListSelect?.length > 0 &&
            <View className="companyListWrap" >
              {
                companyListSelect?.map((v, i) => {
                  return (
                    <View className="companyList" onClick={() => { getEnterVal(v) }} >
                      <Text key={i}>{v.enterpriseName}</Text>
                    </View>
                  )
                })
              }
            </View>
          }

        </View>
        <InputItem
          label={"培训人数"}
          value={number}
          required
          max={5}
          type="number"
          placeholder={"请输入培训人数"}
          onChange={(val) => {
            setNumber(val)
          }}
        />
        <InputItem
          label={"联系人姓名"}
          value={contactName}
          required
          placeholder={"请输入联系姓名"}
          onChange={(val) => {
            setContactName(val)
          }}
        />
        <InputItem
          disabled
          label={"联系电话"}
          value={phone}
          required
          onChange={(val) => {
            setPhone(val)
          }}
        />
        <SelectItem
          label={"培训时间"}
          value={trainingTime}
          required
          placeholder="请选择培训时间"
          onclick={() => {
            setIsVisible2(true)
          }}
        />
        <View className="formtipWrap">
          <Text className="formtip">注:需提前2天预约，上午预约时间为9:00至11:00，下午预约时间为15:00到17:00</Text>
        </View>
        {/* <InputItem
          label={"备注"}
          value={remark}
          style={{ borderBottomLeftRadius: 16, borderBottomRightRadius: 16, }}
          placeholder={"请输入要备注的信息"}
          onChange={(val) => {
            setRemark(val)
          }}
        /> */}
        <View className="remarkWrap">
          <Text className="reTit">备注</Text>
          <Textarea className="remarkSty" placeholder="请输入要备注的信息" onInput={(val) => {
            setRemark(val.detail.value)
          }} />
        </View>
      </View>

      <View className="bottomBtnWrap">
        <Button onclick={() => {
          const errorMessage = verify();
          console.log(errorMessage);
          if (errorMessage) {
            Taro.showToast({
              icon: "none",
              title: errorMessage,
            });

            return;
          }
          setIsVisible4(true)
        }} className="addBtn" size="large" block type="primary" color="#6486FF"> 提交申请 </Button>

      </View>

      <Picker
        title="选择单位所在辖区"
        visible={isVisible1}
        options={areaList}
        onClose={() => setIsVisible1(false)}
        onChange={changePicker}
        onConfirm={(options, values) => {
          let description = ''
          options.forEach((option) => {
            description += ` ${option.text}`
          })
          console.log(description);
          console.log(values.toString());
          setJurisdiction(description)

          setJurisdictionCode(values.toString())
        }}
      />

      <Picker
        title="选择培训时间"
        visible={isVisible2}
        options={timeList}
        onClose={() => setIsVisible2(false)}
        onChange={changePicker}
        onConfirm={(options, values) => {
          // console.log(options);
          // console.log(values);
          // let description = ''
          // options.forEach((option) => {
          //   description += ` ${option.text}`
          // })
          // console.log(values[0]+' '+values[1]);
          setTrainingTime(values[0] + ' ' + values[1])
        }}
      />

      <Picker
        title="选择单位类别"
        visible={isVisible3}
        options={companyList}
        onClose={() => setIsVisible3(false)}
        onChange={changePicker}
        onConfirm={(options, values) => {
          let description = ''
          options.forEach((option) => {
            description += ` ${option.text}`
          })
          setCategory(description)
          setCategoryCode((values).toString())
        }}
      />

      <Dialog
        title="温馨提示"
        visible={isVisible4}
        onConfirm={() => submit()}
        onCancel={() => setIsVisible4(false)}
        footer={(
          <View className="dialogBtnWrap">
            <View>
              <Button block type="default" color="#E8F2FF" style={{ color: '#415FFF' }} onclick={() => setIsVisible4(false)}>取消</Button>
            </View>
            <View>
              <Button block type="info" onclick={() => submit()}>确定</Button>
            </View>
          </View>
        )}
      >
        <View style={{ marginTop: '24px', marginBottom: '24px' }}>
          <Text style={{ color: 'red' }}>请确保提交信息真实有效</Text>
          <Text>，提交后工作人员将在2个工作日内与您联系</Text>
        </View>
      </Dialog>

    </View>
  );
}
